package org.apache.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processcr extends Thread{
	
	private Socket scoket;
	private InputStream is; //输入流
	private PrintStream out; //输出流
	public final static String WEB_ROOT = "/home/feng/develop/workspace/apache/htpdocs";
	
	public Processcr(Socket scoket) {
		this.scoket = scoket;
		try {
			this.is = scoket.getInputStream(); //获取输入流
			this.out = new PrintStream(scoket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		String fileName = this.parse(is);
		this.sendFile(fileName);
	}
	
	/**
	 * 解析请求内容流
	 * @param is
	 * @return
	 */
	public String parse(InputStream is){
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String filename = "";
		try {
			String httpMessage = br.readLine();
			String [] content = httpMessage.split(" ");
			if(content.length != 3){
				this.sendErrorMessage(400, "请求错误");
				return null;
			}
			System.out.println("code=="+content[0] + "  filename=="+content[1] + "  http.version=="+content[2]);
			filename = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;	
		
	}
	
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("HTTP/1.0 "+errorCode + " "+errorMessage);
		out.println("content-type:text/html");
		out.println();
		//返回文件
		out.println("<html>");
		out.println("<title> Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>");
		out.println("ErrorCode:"+errorCode + "ErrorMessage:"+errorMessage);
		out.println("</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		
	}
	
	public void sendFile(String fileName){
		File file = new File(Processcr.WEB_ROOT + fileName);
		if(!file.exists()){
			this.sendErrorMessage(404, "File Not Fourd");
			return ;
		}
		
		try {
			InputStream in = new FileInputStream(file);
			byte [] contents = new byte[(int) file.length()];  //返回文件大小的字节
			in.read(contents);
			//返回http协议的内容
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:"+contents.length);
			out.println();
			out.write(contents);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
